package com.expert.conrtoller;

import com.expert.exception.UpdateException;
import com.expert.result.Result;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @ClassName: PhotoController
 * @Author: cxs
 * @Date: 2024/03/14 21:09
 * @Description:
 **/
@RestController
@RequestMapping("/common")
@Slf4j
public class PhotoController {
    @Value("${expert.expertPhoto.path}")
    String  localPhotoPath;
    /**
     * 上传图片
     *
     * @param file 图片文件
     * @return
     */
    @PostMapping("/upload")
    public Result<String> upload(@RequestBody MultipartFile file) {
        log.info("上传图片：{}", file);
        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取文件后缀
            String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
            String info="['.png', '.jpeg', '.jpg', '.PNG', '.JPG', '.JPEG', '.gif', '.GIF']";
            if (!info.contains(suffix)){
                throw new UpdateException("文件上传失败！");
            }
            String newFileName= UUID.randomUUID()+suffix;
            File uploadFile = new File(localPhotoPath + newFileName);
            if (!uploadFile.getParentFile().exists()){
                uploadFile.getParentFile().mkdirs();
            }
            // 上传文件到磁盘
            file.transferTo(uploadFile);
            // 数据库若不存在重复文件，则不删除刚才上传的文件
            return Result.success(newFileName);
        } catch (IOException e) {
            log.error("文件上传失败{}", e);
        }
        return Result.error("文件上传失败！",0);
    }
}
